<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
        <link rel="stylesheet" href="css/gstyle.css" />
        <script src="js/jquery-1.7.1.min.js"></script>
        <title>ZenTxt</title>
        <link rel="stylesheet" href="codemirror/lib/codemirror.css">
        <script src="codemirror/lib/codemirror.js"></script>
        <link rel="stylesheet" href="codemirror/theme/eclipse.css">
        <script src="codemirror/mode/xml/xml.js"></script>
        <link rel="stylesheet" href="codemirror/doc/docs.css">
        <script>
            var current_file_id="";
            function set_file_id(id) {
                current_file_id=id;
                //sessionstorage.setItem("fileid", id);
            }
            function get_file_id() {
                return current_file_id;
                //return sessionstorage.getItem("fileid");
            }

            var editor;
            function create_editor() {
                editor = CodeMirror.fromTextArea(document.getElementById("content"), {
                    lineNumbers: false,
                    theme: "eclipse",
                    //saveFunction: function() { alert("saveFunction"); OnTextareaKeyDown(); },
                    extraKeys: {
                        "F11": function() {
                          var scroller = editor.getScrollerElement();
                          if (scroller.className.search(/\bCodeMirror-fullscreen\b/) === -1) {
                            scroller.className += " CodeMirror-fullscreen";
                            scroller.style.height = "100%";
                            scroller.style.width = "100%";
                            editor.refresh();
                          } else {
                            scroller.className = scroller.className.replace(" CodeMirror-fullscreen", "");
                            scroller.style.height = '';
                            scroller.style.width = '';
                            editor.refresh();
                          }
                        },
                        "Esc": function() {
                          var scroller = editor.getScrollerElement();
                          if (scroller.className.search(/\bCodeMirror-fullscreen\b/) !== -1) {
                            scroller.className = scroller.className.replace(" CodeMirror-fullscreen", "");
                            scroller.style.height = '';
                            scroller.style.width = '';
                            editor.refresh();
                          }
                        },
                    }
                });
            }
            
            var content_changed=false;
            var old_content="";
            function save_file_content() {
                //if(true == content_changed) {
                if(old_content != new_content) {
                    //var new_content = $("#content").val();
                    var new_content = editor.getValue();
                    //alert(new_content);
                    var file_id=get_file_id();
                    console.log("Saving file " + file_id);
                    var data;
                    $.post("/save", { id: file_id, content: new_content },
                       function(data) {
                            content_changed = false;
                            old_content = new_content;
                            load_revisions(file_id)
                       });
                }
            }
            function load_file(file_id) {
                save_file_content();
                $("#revision").hide();
                $("#listview").hide();
                $("#editor").show();
                $("#content").text("");
                console.log("Loading file " + file_id);
                var url="/file?id=" + file_id;
                var data;
                $.get(url, function(data) {
                    //$("#content").val(data);
                    editor.setValue(data);
                    old_content = data;
                    set_file_id( file_id );
                    load_revisions( file_id );
                    set_file_name( file_id );
                });
            }
            
            function set_file_name(file_id) {
                var url="/fileinfo?id=" + file_id;
                var data;
                $.getJSON(url, function(data) {
                    $(".filename").text(data.name);
                });
            }
            
            function rename_file() {
                var file_name = prompt("Please enter new name","");
                if(file_name.length > 0) {
                    var file_id=get_file_id();
                    $.post("/rename", { id: file_id, name: file_name },
                       function(data) {
                            set_file_name(file_id);
                            load_files();
                       });
                }
            }

            function create_new_file() {
                save_file_content();
                var file_name = prompt("Please enter file name","New File");
                if(file_name.length > 0) {
                    $.post("/newfile", { name: file_name },
                       function(data) {
                            load_file(data);
                            load_files();
                       });
                }
            }

            function load_revision(rev_id)
            {
                console.log("Loading revision " + rev_id);
                var url="/rev?id=" + rev_id;
                var data;
                $.get(url, function(data) {
                    $("#revision").html(data);
                    $("#editor").hide();
                    $("#listview").hide();
                    $("#revision").show();
                });
            }

            function load_revisions(file_id) {
                var list_id="#rev_list";
                $(list_id).children().remove();
                var el = "<li><a href='#' onclick='show_all_revisions()'>Show all</a></li>";
                $(list_id).append(el);
                el = "<li class='menuseprator'></li>"
                $(list_id).append(el);
                var url="/revisions?file=" + file_id + "&max=15";
                $.getJSON(url, function(data) {
                    $.each(data.revision, function(index, revision) {
                        //console.log(revision);
                        if(revision.key.length > 0) {
                            url="load_revision('"+revision.key+"')";
                            var el = "<li><a href='#' onclick="+url+">"+revision.date+"</a></li>";
                            $(list_id).append(el);
                        }
                    });
                });
            }

            function preview_revision(key) {
                //alert("onclick");
                var el = $("#"+key);
                if( el.is(':visible') ) {
                    el.hide();
                } else {
                    var rev_text = el.html();
                    console.log(rev_text);
                    if (rev_text.length == 0) {
                        var url="/rev?id=" + key;
                        var data;
                        $.get(url, function(data) {
                            el.html(data);
                        });
                    }
                    el.show();
                }
            }

            function show_all_revisions() {
                $("#editor").hide();
                $("#listview").show();
                $("#revision").hide();
                var file_id=get_file_id();
                var list_id="#file_list_full";
                $(list_id).children().remove();
                var url="/revisions?file=" + file_id + "&max=15";
                $.getJSON(url, function(data) {
                    $.each(data.revision, function(index, revision) {
                        //console.log(revision);
                        if(revision.key.length > 0) {
                            url="preview_revision('"+revision.key+"')";
                            var el = "<li><a href='#' onclick="+url+">"+revision.date+"</a><div id='"+revision.key+"' style='display: none;'></div></li>";
                            $(list_id).append(el);
                        }
                    });
                });
            }

            function load_files() {
                var list_id="#file_list";
                $(list_id).children().remove();
                var el = "<li><a href='#' onclick='rename_file()'>Rename</a></li>";
                $(list_id).append(el);
                var el = "<li><a href='#' onclick='create_new_file()'>New file</a></li>";
                $(list_id).append(el);
                var el = "<li><a href='#' onclick='show_all_files()'>Show all</a></li>";
                $(list_id).append(el);
                el = "<li class='menuseprator'></li>"
                $(list_id).append(el);
                $.getJSON("/files?max=15", function(data) {
                    $.each(data.file, function(index, file) {
                        //console.log(file);
                        if(file.name.length > 0) {
                            url="load_file('" + file.key + "')";
                            var el = "<li><a href='#' onclick="+url+">"+file.name+"</a></li>";
                            $(list_id).append(el);
                        }
                    });
                });
            }

            function load_last_file()
            {
                var data;
                $.get("/last", function(data) {
                    load_file( data );
                });
            }

            function reload_file() {
                load_file( get_file_id() );
            }

            function load_suggestions() {
                var data;
                $.get("/suggestions", function(data) {
                    load_file( data );
                });
            }
            
            function show_all_files() {
                $("#editor").hide();
                $("#listview").show();
                $("#revision").hide();
                var list_id="#file_list_full";
                $(list_id).children().remove();
                $.getJSON("/files", function(data) {
                    $.each(data.file, function(index, file) {
                        //console.log(file);
                        if(file.name.length > 0) {
                            url="load_file('" + file.key + "')";
                            var el = "<li><a href='#' onclick="+url+">"+file.name+"</a></li>";
                            $(list_id).append(el);
                        }
                    });
                });
            }

            function OnLoad()
            {
                load_files();
                load_last_file();
            }

            function OnUnload()
            {
                save_file_content();
            }
            
            function OnTextareaKeyDown() {
                //editor.save();
                //var new_content = $("#content").val();
                new_content = editor.getValue();
                if(old_content != new_content) {
                    content_changed = true;
                }
            }

            $.ctrl = function(key, callback, args) {
                var isCtrl = false;
                $(document).keydown(function(e) {
                    if(!args) args=[]; // IE barks when args is null

                    if(e.ctrlKey) isCtrl = true;
                    if(e.keyCode == key.charCodeAt(0) && isCtrl) {
                        callback.apply(this, args);
                        return false;
                    }
                }).keyup(function(e) {
                    if(e.ctrlKey) isCtrl = false;
                });
            };
            $.ctrl('S', function() {
                save_file_content();
            });
            function checkKeyCode(evt)
            {
                var evt = (evt) ? evt : ((event) ? event : null);
                var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
                if(event.keyCode==116)
                {
                    //alert("Refresh");
                    load_last_file();
                    evt.keyCode=0;
                    return false
                }
            }
            document.onkeydown=checkKeyCode;

        </script>
        <style type="text/css">
            .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
            .CodeMirror-fullscreen {
                display: block;
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 9999;
                margin: 0;
                padding: 0;
                border: 0px solid #BBBBBB;
                opacity: 1;
            }
        </style>
    </head>
    <body onbeforeunload="OnUnload()" onload="OnLoad()">
        <div id="wrapper">
            <div id="navwrapper">  
                <ul id="nav" class="floatleft">
{% if user %}
                    <!--li><a href="#">History</a></li-->
                    <li>
                        <a class="dmenu" href="#" onclick="load_last_file()"><span class="filename">Files</span><span class="arrowdown">▼</span></a>  
                        <ul id="file_list">  
                            <li><a href="#">file</a></li>  
                            <!--li class="menuseprator"></li>  
                            <li><a href="#">Even More »</a></li-->
                        </ul>  
                    </li>  
{% endif %}
                    <li>
                        <a class="dmenu" href="#">Revisions <span class="arrowdown">▼</span></a>  
                        <ul id="rev_list">  
                            <li><a href="#">revision</a></li>  
                            <li class="menuseprator"></li>  
                        </ul>  
                    </li>  
                    <li><a href="#" onclick="load_suggestions()">Suggestions</a></li>  
                </ul>
                <ul id="nav" class="floatright">  
{% if user %}
			        <li><a href="#">{{ user }}</a></li>
                    <!--li><a href="#">Settings</a></li-->
                    <li><a href="{{ logout_url }}">Logout</a></li>  
{% else %}
                    <li><a href="{{ login_url }}">Login</a></li>
{% endif %}
                </ul>  
              
                <br class="clear">  
            </div>  

            <div id="editor" class="editor">
                <textarea id="content" cols="1" rows="1" onkeydown="OnTextareaKeyDown()">Hello World!</textarea>
            </div>
            <script>
                create_editor();
            </script>
            <div id="revision" class="editor" style="background-color: #555555; overflow:scroll;"></div>
            <div id="listview" class="editor" style="background-color: #555555; overflow:scroll;">
                <ul id="file_list_full">
                  <li>
                  </li>
                </ul>
            </div>
        </div>
    </body>
</html>

